package org.seoul.gtugs.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.seoul.gtugs.client.PhotoUploadService;
import org.seoul.gtugs.shared.PhotoEntity;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class PhotoUploadServiceImpl extends RemoteServiceServlet implements
PhotoUploadService {
	DatastoreService datastore;
	
	public PhotoUploadServiceImpl() {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}	
	
	@Override
	public String getBlobstoreUploadUrl() {
		BlobstoreService blobstoreService = BlobstoreServiceFactory
				.getBlobstoreService();
		return blobstoreService.createUploadUrl("/upload");
	}

	@Override
	public PhotoEntity get(String encodedKey) {
		Key key = KeyFactory.stringToKey(encodedKey);
		try {
			Entity result = datastore.get(key);
	
			PhotoEntity image = new PhotoEntity();
			image.setServingUrl((String) result.getProperty("serveUrl"));
			image.setOwnerId((String) result.getProperty("ownerId"));
			image.setKey(encodedKey);
			
			return image;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	@Override
	public List<PhotoEntity> listPhotos() {
		Query qry = new Query("UploadedImage");
		PreparedQuery pq = datastore.prepare(qry);
		List<PhotoEntity> lists = new ArrayList<PhotoEntity>();
		
		for (Entity result : pq.asIterable()) {
			  String serveUrl = (String) result.getProperty("serveUrl");
			  String ownerId = (String) result.getProperty("ownerId");
			  PhotoEntity ent = new PhotoEntity();
			  ent.setServingUrl(serveUrl);
			  ent.setOwnerId(ownerId);
			  lists.add(ent);
		}
		
		return lists;
	}

}